import React, { useState, useRef, useEffect } from 'react';

const Captcha = (props) => {
    // 随机生成的验证码
  const [captchaText, setCaptchaText] = useState('');
  const canvasRef = useRef(null);

  // 生成随机验证码
  const generateCaptcha = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let captcha = '';
    for (let i = 0; i < 6; i++) {
      captcha += chars[Math.floor(Math.random() * chars.length)];
    }
    setCaptchaText(captcha);
    props.login(captcha)
    drawCaptcha(captcha);
  };

  // 绘制验证码到canvas
  const drawCaptcha = (text) => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 设置背景色
    ctx.fillStyle = '#f0f0f0';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 设置文字样式
    ctx.font = 'bold 30px Arial';
    ctx.fillStyle = '#000';

    // 扭曲文字
    for (let i = 0; i < text.length; i++) {
      ctx.save();
      // 随机偏移和旋转
      ctx.translate(20 + i * 20, 30);
      ctx.rotate((Math.random() - 0.5) * 0.4);
      ctx.fillText(text[i], 0, 0);
      ctx.restore();
    }

    // 添加干扰线
    for (let i = 0; i < 5; i++) {
      ctx.strokeStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.8)`;
      ctx.beginPath();
      ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.stroke();
    }

    // 添加噪点
    for (let i = 0; i < 100; i++) {
      ctx.fillStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.8)`;
      ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 2, 2);
    }
  };


  // 初始化时生成验证码
  useEffect(() => {
    generateCaptcha();
  }, []);

  return (
    <div>
      <canvas ref={canvasRef} width="150" height="50" onClick={generateCaptcha} style={{margin:'0 0 2vh 0'}}></canvas>
    </div>
  );
};

export default Captcha;